package com.jianying.day05;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * ClassName: Flink04_Window_reduce
 * Package: com.atguigu.day05
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/3 14:24
 * @Version: 1.0
 */
public class Flink05_Window_aggregate {
    public static void main(String[] args) throws Exception {
        // TODO 开滚动处理时间窗口，使用aggregate对窗口中元素进行聚合
        // 取出最近10s中每个传感器采集到的水位的和
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 8888);
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());

        // TODO 按照ID 分组
        KeyedStream<WaterSensor, String> keyByDS = wsDS.keyBy(ws -> ws.getId());

        // TODO 开窗 滚动处理时间窗口，大小10s
        WindowedStream<WaterSensor, String, TimeWindow> windowDS = keyByDS.window(
                TumblingProcessingTimeWindows.of(Time.seconds(10))
        );

        // TODO 对窗口中的数据进行聚合计算 aggretate  窗口中三个类型可以不一致
        SingleOutputStreamOperator<String> aggregateDS = windowDS.aggregate(
                new AggregateFunction<WaterSensor, Integer, String>() {
                    @Override
                    public Integer createAccumulator() {
                        return 0;
                    }

                    @Override
                    public Integer add(WaterSensor waterSensor, Integer integer) {
                        return integer + waterSensor.getVc();
                    }

                    @Override
                    public String getResult(Integer integer) {
                        return integer + "";
                    }

                    @Override
                    public Integer merge(Integer integer, Integer acc1) {
                        return null;
                        // TODO 只有会话窗口需要做 看源码 5-15 5-16窗口对象
                    }
                }
        );

        // TODO 打印输出
        aggregateDS.print();

        env.execute();
    }
}
